import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  addMultiplexItemAPI,
  getMultiplexListAPI,
  deleteMultiplexItemAPI,
  updateMultiplexItemAPI
} from '@/http/multiplex'
import type { WordListItemTypeArr } from '@/interface/word/wordType'

export const useWordStore = defineStore('word', () => {
  const list = ref<WordListItemTypeArr>([])
  const total = ref(0)
  const addWordItemAction = async (path: string, data: any) => {
    try {
      let res: any = await addMultiplexItemAPI(path, data)
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: res.message
        })
        return 200
      } else {
        ElMessage({
          type: 'error',
          message: res.message
        })
      }
    } catch (error) {
      console.log('添加失败')
    }
  }
  const getListAction = async (path: string, data: any) => {
    try {
      let res: any = await getMultiplexListAPI(path, data)
      list.value = res.data
      total.value = res.totalCount
      return {
        code: res.code,
        message: res.message
      }
    } catch (error) {
      console.log('获取列表失败')
    }
  }
  const deleteListItem = async (path: string, id: string) => {
    try {
      let res: any = await deleteMultiplexItemAPI(path, id)
      if (res.code === 200) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        // 设计有点问题，应该将页码之类的默认参数放在pinia中
        await getListAction(path, { page: 1, pageSize: 5 }) //重新获取最新列表数据
      } else {
        ElMessage({
          message: '删除失败',
          type: 'error'
        })
      }
    } catch (error) {
      console.log('删除失败')
    }
  }
  const updateInfo = async (path: string, id: string, data: any) => {
    try {
      let res: any = await updateMultiplexItemAPI(path, id, { ...data, updatetime: Date.now() })
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '更新成功！'
        })
        // 重新获取列表数据
        await getListAction(path, { page: 1, pageSize: 5 })
        return res.code
      } else {
        ElMessage({
          type: 'warning',
          message: '更新失败'
        })
      }
    } catch (error) {
      console.log('更新数据失败')
    }
  }
  return { list, total, addWordItemAction, getListAction, deleteListItem, updateInfo }
})
